﻿
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EMSSevice;
using Microsoft.Extensions.DependencyInjection;
using BusinessService.Plugin.DataSource.Sqlite;
using AntdUI;
using BusinessService.Plugin.Const;
using BusinessService.Plugin.DataSource.Sqlite.Dtos;
using BusinessService.Plugin.Entity;
using WindowsForm.FormDtos;
using Mapster;
using BusinessService.Plugin.Services;

namespace WindowsForm.Forms
{
    public partial class DBConnection : UserControl
    {
        private BackService _backService => Program.IOC.GetRequiredService<BackService>();

        private SqliteLibrary _repSqlite => Program.IOC.GetRequiredService<SqliteLibrary>();
        public DBConnection()
        {
            InitializeComponent();


            DBselect.Items.Add("MySql");
            DBselect.Items.Add("QuestDB");


            Http_method.Items.Add("Post");
            Http_method.Items.Add("Get");
            TCP_select.Items.Add("客户端");
            TCP_select.Items.Add("服务器");

            //Http初始化
            UpdateTable(Http_Table, TypeEnum.Http.ToString());
            Http_Table.CellButtonClick += table_CellButtonClick;
            //socket初始化
            UpdateTable(TCP_Table, TypeEnum.Socket.ToString());
            TCP_Table.CellButtonClick += table_CellButtonClick;
            //Mqtt初始化
            UpdateTable(MQTT_table, TypeEnum.MQTT.ToString());
            MQTT_table.CellButtonClick += table_CellButtonClick;

        }

        /// <summary>
        /// ID暂存
        /// </summary>
        long Http_ID, MQTT_ID, Socket_ID = 0;
        private void DBConnection_Load(object sender, EventArgs e)
        {
            inputConnectionStr.Text = Settings1.Default.ConnectionStr;
            DBselect.Text = Settings1.Default.DBselect;
        }

        private void input1_TextChanged(object sender, EventArgs e)
        {

        }
        #region 数据库连接
        private void button2_Click(object sender, EventArgs e)
        {

            try
            {
                //创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
                using (SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = inputConnectionStr.Text,
                    DbType = DBselect.Text.Equals("MySql".Trim())? SqlSugar.DbType.MySql: SqlSugar.DbType.QuestDB,
                    IsAutoCloseConnection = true,
                }))
                {
                    var state = Db.Ado.GetInt("SELECT 1") > 0;
                    string result = string.Empty;
                    if (state)
                    {
                        result = "连接测试成功！";

                    }
                    else
                    {
                        result = "连接测试失败！";

                    }
                    MessageBox.Show(result, "连接测试结果");


                }

            }
            catch (Exception)
            {

                MessageBox.Show("连接测试失败！", "信息提示");
                return;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Settings1.Default.ConnectionStr = inputConnectionStr.Text;
            Settings1.Default.DBselect = DBselect.Text;
            Settings1.Default.Save();
            MessageBox.Show("数据库连接字符串保存成功！", "信息提示");
        }
        #endregion


        /// <summary>
        /// 更新表格数据
        /// </summary>
        /// <param name="table"></param>
        private void UpdateTable(Table table, string ProtocolType)
        {


            AllSetQueryInput input = new AllSetQueryInput();
            input.N_Role = 1;//设置发送端查询
            input.V_ProtocolType = ProtocolType;//设置协议类型
            var list = _repSqlite.AllSetQuery(input);

            var Dto = list.Adapt<List<AllSetDtos>>();

            Dto.ForEach(x =>
            {
                x.Btns = new AntdUI.CellLink[] {
                    new AntdUI.CellButton("edit","编辑",AntdUI.TTypeMini.Primary) {  Ghost = true,BorderWidth=1 },
                    new AntdUI.CellButton("delete","删除",AntdUI.TTypeMini.Error) {  Ghost = true ,BorderWidth=1}
                };
            });
            table.DataSource = Dto;//赋值

            switch (input.V_ProtocolType)
            {
                case "Socket":// 添加表头，绑定模型名称
                    table.Columns = new AntdUI.Column[] {
                       new AntdUI.Column("N_Id", "ID"),
                      new AntdUI.Column("V_Name","通道名称"),
                       new AntdUI.Column("TCP_Role", "本机角色") ,
                       new AntdUI.Column("IP", "IP"),
                       new AntdUI.Column("Port","端口号"),
                       new AntdUI.Column("Btns", "操作") ,

            }; break;
                case "MQTT":// 添加表头，绑定模型名称
                    table.Columns = new AntdUI.Column[] {
                      new AntdUI.Column("N_Id", "ID"),
                         new AntdUI.Column("V_Name","通道名称"),
                       new AntdUI.Column("IP", "IP"),
                       new AntdUI.Column("Port","端口号"),
                       new AntdUI.Column("MQTT_UserName", "用户名"),
                       new AntdUI.Column("MQTT_PassWord","密码"),
                           new AntdUI.Column("MQTT_Topics","主题"),
                       new AntdUI.Column("Btns", "操作") ,

            }; break;

                case "Http":// 添加表头，绑定模型名称
                    table.Columns = new AntdUI.Column[] {
                       new AntdUI.Column("N_Id", "ID"),
                          new AntdUI.Column("V_Name","通道名称"),
                       new AntdUI.Column("Http_Method", "发送方式"),
                       new AntdUI.Column("Http_Url","Url地址"),
                       new AntdUI.Column("Http_Token", "授权"),
                       new AntdUI.Column("Btns", "操作") ,

            }; break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 表格按钮操作事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="btn"></param>
        /// <param name="args"></param>
        /// <param name="record"></param>
        /// <param name="rowIndex"></param>
        /// <param name="columnIndex"></param>
        private void table_CellButtonClick(object sender, AntdUI.CellLink btn, MouseEventArgs args, object record, int rowIndex, int columnIndex)
        {
            if (SqlFunc.IsNullOrEmpty(btn)) return;
            var selectRow = (AllSetDtos)record;
            if (btn.Text.Equals("删除"))
            {

                if (selectRow != null)
                {
                    _repSqlite.AllSetDelete(selectRow.N_Id);//删除指定行    
                    switch (selectRow.V_ProtocolType)
                    {
                        case "Socket": UpdateTable(TCP_Table, TypeEnum.Socket.ToString()); break;
                        case "MQTT": UpdateTable(MQTT_table, TypeEnum.MQTT.ToString()); break;
                        case "Http": UpdateTable(Http_Table, TypeEnum.Http.ToString()); break;
                        default:
                            break;
                    }
                };
            }

            if (btn.Text.Equals("编辑"))
            {
                switch (selectRow.V_ProtocolType)
                {
                    case "Socket":
                        TCP_inputName.Text = selectRow.V_Name;
                        TCP_inputIP.Text = selectRow.IP;
                        TCP_inputPort.Text = selectRow.Port.ToString();
                        TCP_select.Text = selectRow.TCP_Role;
                        Socket_ID = selectRow.N_Id;
                        ; break;
                    case "MQTT":
                        inputMQTT_Name.Text = selectRow.V_Name;
                        inputMQTT_IP.Text = selectRow.IP;
                        inputMQTT_Port.Text = selectRow.Port.ToString();
                        inputMQTT_UserName.Text = selectRow.MQTT_UserName;
                        inputMQTT_Password.Text = selectRow.MQTT_PassWord;
                        inputMQTT_Topic.Text = selectRow.MQTT_Topics;
                        MQTT_ID = selectRow.N_Id;
                        break;
                    case "Http":
                        Http_inputName.Text = selectRow.V_Name;
                        Http_method.Text = selectRow.Http_Method;
                        Http_Url.Text = selectRow.Http_Url;
                        Http_ID = selectRow.N_Id;
                        Http_Token.Text = selectRow.Http_Token;
                        break;
                    default:
                        break;
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {


                AllSet input = new AllSet();
                if (Socket_ID == 0)
                {
                    Socket_ID = -1;
                }
                input.V_Name = TCP_inputName.Text;
                input.N_Id = Socket_ID;
                input.N_Role = 1;
                input.V_ProtocolType = TypeEnum.Socket.ToString();
                input.TCP_Role = TCP_select.Text;
                input.IP = TCP_inputIP.Text;
                input.Port = int.Parse(TCP_inputPort.Text);
                _repSqlite.AllSetEdit(input);
                StaticResource.Tcp_Role = input.TCP_Role;
                UpdateTable(TCP_Table, TypeEnum.Socket.ToString());
            }
            catch (System.FormatException)
            {
                MessageBox.Show("数据格式编辑有误,端口号编辑输入不允许空!", "提示");
                return;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            AllSet input = new AllSet();
            input.N_Id = 0;
            input.N_Role = 1;
            input.V_ProtocolType = TypeEnum.Socket.ToString();
            input.V_Name = TCP_inputName.Text;
            input.TCP_Role = TCP_select.Text;
            input.IP = TCP_inputIP.Text;
            input.Port = int.Parse(TCP_inputPort.Text);
            _repSqlite.AllSetEdit(input);
            StaticResource.Tcp_Role = input.TCP_Role;
            UpdateTable(TCP_Table, TypeEnum.Socket.ToString());
            //MessageBox.Show("参数保存成功！", "消息提示");
        }

        private void TCP_Table_CellClick_1(object sender, MouseEventArgs args, object record, int rowIndex, int columnIndex, Rectangle rect)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            AllSet input = new AllSet();
            try
            {
                input.N_Id = 0;
                input.N_Role = 1;
                input.V_ProtocolType = TypeEnum.MQTT.ToString();
                input.V_Name = inputMQTT_Name.Text;
                input.IP = inputMQTT_IP.Text;
                input.Port = int.Parse(inputMQTT_Port.Text);
                input.MQTT_UserName = inputMQTT_UserName.Text;
                input.MQTT_PassWord = inputMQTT_Password.Text.Trim();
                input.MQTT_Topics = inputMQTT_Topic.Text;
                _repSqlite.AllSetEdit(input);
                StaticResource.Tcp_Role = input.TCP_Role;
                UpdateTable(MQTT_table, TypeEnum.MQTT.ToString());
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            AllSet input = new AllSet();
            if (MQTT_ID == 0)
            {
                MQTT_ID = -1;
            }
            try
            {
                input.N_Id = MQTT_ID;
                input.N_Role = 1;
                input.V_ProtocolType = TypeEnum.MQTT.ToString();
                input.V_Name = inputMQTT_Name.Text;
                input.IP = inputMQTT_IP.Text;
                input.Port = int.Parse(inputMQTT_Port.Text);
                input.MQTT_UserName = inputMQTT_UserName.Text;
                input.MQTT_PassWord = inputMQTT_Password.Text.Trim();
                input.MQTT_Topics = inputMQTT_Topic.Text;
                _repSqlite.AllSetEdit(input);
                StaticResource.Tcp_Role = input.TCP_Role;
                UpdateTable(MQTT_table, TypeEnum.MQTT.ToString());
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                AllSet input = new AllSet();
                if (Http_ID == 0)
                {
                    Http_ID = -1;
                }
                input.N_Id = Http_ID;
                input.N_Role = 1;
                input.V_Name = Http_inputName.Text;
                input.V_ProtocolType = TypeEnum.Http.ToString();

                input.Http_Method = Http_method.Text;
                input.Http_Url = Http_Url.Text;
                input.Http_Token = Http_Token.Text;
                _repSqlite.AllSetEdit(input);
                //StaticResource.Tcp_Role = input.TCP_Role;
                UpdateTable(Http_Table, TypeEnum.Http.ToString());
            }
            catch (System.FormatException)
            {
                MessageBox.Show("数据格式编辑有误,端口号编辑输入不允许空!", "提示");
                return;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            AllSet input = new AllSet();
            input.N_Id = 0;
            input.N_Role = 1;
            input.V_Name = Http_inputName.Text;
            input.V_ProtocolType = TypeEnum.Http.ToString();

            input.Http_Method = Http_method.Text;
            input.Http_Url = Http_Url.Text;

            _repSqlite.AllSetEdit(input);
            //StaticResource.Tcp_Role = input.TCP_Role;
            UpdateTable(Http_Table, TypeEnum.Http.ToString());
            //MessageBox.Show("参数保存成功！", "消息提示");
        }

        private void Http_Table_CellClick(object sender, MouseEventArgs args, object record, int rowIndex, int columnIndex, Rectangle rect)
        {

        }
    }
}
